<template>
  <g-dynamic-table
    type="organization-unit-members"
    ref="table"
    class="dynamic-table"
    :fetch="fetchDataList"
    @action-click="handleActionClick"
    :extraHeight="48"
    :showExport="true"
  >
  </g-dynamic-table>
</template>

<script lang="ts">
  import {
    OrganizationUnitListDto,
    OrganizationUnitServiceProxy,
    IPagedResultDtoOfOrganizationUnitUserListDto,
  } from '/@/shared/service-proxies';
  import { PlusOutlined, DeleteOutlined, ReloadOutlined } from '@ant-design/icons-vue';
  import AddMemberComponent from '../add-member/add-member.vue';
  import { defineComponent } from 'vue';
  import _ from 'lodash';
  import GDynamicTable from '/@/shared/components/g-dynamic-table/index.vue';
  import AppCompoentBase from '/@/shared/component-base/app-component-base';
  import { EVENT_BTN_ENUM } from '/@/shared/components/g-dynamic-table/enums/event-btn-enum';
  import dayjs from 'dayjs';
  import { jsonToSheetXlsx } from '/@/components/Excel';
  import { AppConsts } from '/@/abpPro/AppConsts';
  export default defineComponent({
    name: 'organization-unit-members-panel',
    components: {
      GDynamicTable,
      PlusOutlined,
      DeleteOutlined,
      ReloadOutlined,
      AddMemberComponent,
    },
    mixins: [AppCompoentBase],
    props: {
      selectTree: OrganizationUnitListDto,
    },
    data() {
      return {
        organizationUnitServiceProxy: new OrganizationUnitServiceProxy(this.$apiUrl, this.$api),
      };
    },
    watch: {
      'selectTree.id': {
        handler() {
          this.refresh();
        },
      },
    },
    methods: {
      refresh() {
        (this.$refs.table as any).reload();
      },
      fetchDataList(otherQuery) {
        const { maxResultCount, skipCount, UserName, sorting } = (
          this.$refs.table as any
        ).getSearchProps();
        return new Promise((resolve, reject) => {
          if (!this.selectTree || !this.selectTree.id) {
            reject();
            return;
          }
          this.organizationUnitServiceProxy
            .getPagedOrganizationUnitUsers(
              this.selectTree?.id,
              UserName,
              sorting,
              !!otherQuery ? otherQuery.maxResultCount : maxResultCount,
              !!otherQuery ? otherQuery.skipCount : skipCount,
            )
            .then((res) => {
              resolve(res);
            })
            .catch((error) => {
              reject(error);
            });
        });
      },
      /** 导出Excel */
      exportFetch({ id, userName, sorting, maxResultCount, skipCount }) {
        (this.$refs.table as any).setLoading(true);
        this.organizationUnitServiceProxy
          .getPagedOrganizationUnitUsers(id, userName, sorting, maxResultCount, skipCount)
          .then((res: IPagedResultDtoOfOrganizationUnitUserListDto) => {
            if (!!res.items) {
              const data = !!res.items
                ? res.items.map((item) => {
                    const obj: any = item;
                    obj.addedTime = dayjs(obj.addedTime).format('YYYY-MM-DD HH:mm:ss');
                    return obj;
                  })
                : [];
              jsonToSheetXlsx({
                data,
                filename: '组织单元-用户.xlsx',
              });
              abp.notify.success(this.l('ExportSuccess'));
            }
          })
          .finally(() => {
            (this.$refs.table as any).setLoading(false);
          });
      },
      /** 按钮点击事件 */
      handleActionClick(event: string, item?: any) {
        const { maxResultCount, skipCount, userName, sorting } = (
          this.$refs.table as any
        ).getSearchProps();
        switch (event) {
          case EVENT_BTN_ENUM.CREATE:
            this.addUser();
            break;
          case EVENT_BTN_ENUM.DELETE:
            this.removeMember(item);
            break;
          case EVENT_BTN_ENUM.BULK_DELETE:
            this.batchDelete();
            break;
          case EVENT_BTN_ENUM.EXPORT:
            if (!this.selectTree || !this.selectTree.id) {
              return;
            }
            this.exportFetch({
              id: this.selectTree?.id,
              userName,
              sorting,
              maxResultCount,
              skipCount,
            });

            break;
          case EVENT_BTN_ENUM.BULK_EXPORT:
            if (!this.selectTree || !this.selectTree.id) {
              return;
            }
            this.exportFetch({
              id: this.selectTree?.id,
              userName: '',
              sorting: '',
              maxResultCount: AppConsts.export.maxResultCount,
              skipCount: AppConsts.export.skipCount,
            });
            break;
          default:
            break;
        }
      },
      /**
       * 移除用户
       * @param user 当前用户实体
       */
      removeMember(user: OrganizationUnitListDto) {
        const _ouId = parseInt(this.selectTree?.id ?? '');
        this.organizationUnitServiceProxy.removeUser(user.id, _ouId).then(() => {
          this.notify.success(this.l('SuccessfullyDeleted'));
          if ((this.$refs.table as any).getDataSource().length <= 1) {
            (this.$refs.table as any).reloadGoFirstPage();
          } else {
            this.refresh();
          }
        });
      },
      /**
       * 批量删除
       */
      batchDelete() {
        const table = this.$refs.table as any;
        const selectCount = table.getSelectRowKeys().length;
        if (selectCount <= 0) {
          this.message.warn(this.l('PleaseSelectAtLeastOneItem'));
          return;
        }
        this.message.confirm(
          this.l('ConfirmDeleteXItemsWarningMessage', selectCount),
          '',
          (res) => {
            if (res) {
              const _ouId = parseInt(this.selectTree?.id ?? '');
              this.organizationUnitServiceProxy
                .batchRemoveUserFromOrganizationUnit(_ouId, table.getSelectRowKeys())
                .then(() => {
                  this.notify.success(this.l('SuccessfullyDeleted'));
                  if ((this.$refs.table as any).getDataSource().length <= selectCount) {
                    (this.$refs.table as any).reloadGoFirstPage();
                  } else {
                    this.refresh();
                  }
                });
            }
          },
        );
      },
      /**
       * 增加用户
       */
      addUser() {
        this.modalHelper
          .create(AddMemberComponent, {
            organizationUnitId: parseInt(this.selectTree?.id ?? ''),
          })
          .subscribe((res) => {
            if (res) {
              this.refresh();
            }
          });
      },
    },
  });
</script>

<style scoped lang="less">
  .dynamic-table {
    padding: 0;

    :deep(.toolbar-area) {
      margin-bottom: 10px;
    }
  }
</style>
